package com.yourenbang.lingyun.transaction.web.controller.yxy;

import com.alibaba.fastjson.JSONObject;
import com.yourenbang.lingyun.constants.enums.pay.PayFromEnum;
import com.yourenbang.lingyun.constants.enums.pay.PayTypeEnum;
import com.yourenbang.lingyun.core.base.interceptor.ExcludeInterceptor;
import com.yourenbang.lingyun.core.message.Result;
import com.yourenbang.lingyun.core.util.StringUtils;
import com.yourenbang.lingyun.core.util.encrypt.hlb.HlbCommonUtils;
import com.yourenbang.lingyun.core.util.encrypt.hlb.HlbSignUtils;
import com.yourenbang.lingyun.core.util.encrypt.lkl.RSAUtil;
import com.yourenbang.lingyun.core.util.encrypt.xiaolu.XiaoLuUtil;
import com.yourenbang.lingyun.core.util.encrypt.ydc.YdcDecryptUtil;
import com.yourenbang.lingyun.core.util.encrypt.yilian.YiLianUtil;
import com.yourenbang.lingyun.core.util.encrypt.yisheng.DecryptUtil;
import com.yourenbang.lingyun.core.util.http.RequestUtil;
import com.yourenbang.lingyun.transaction.config.AcmTransactionParams;
import com.yourenbang.lingyun.transaction.web.domain.dto.LakalaCallBackDTO;
import com.yourenbang.lingyun.transaction.web.service.CommonService;
import com.yourenbang.lingyun.transaction.web.service.yxy.XiaoLuTradeService;
import com.yourenbang.lingyun.transaction.web.service.yxy.YishengTradeService;
import com.yourenbang.lingyun.transaction.web.service.yxy.YxyTradeJhmpService;
import com.yourenbang.lingyun.transaction.web.service.yxy.YxyTradeService;
import com.yourenbang.transaction.api.service.pay.PayTypeApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Objects;

/**
 * @Description
 * @Date 2021/4/24 13:44
 * @Created by Jason
 */

@Slf4j
@RestController
@RequestMapping("/transaction/jbp/callback")
public class YxyCallBackController {

    @Autowired
    private YxyTradeService yxyTradeService;
    @Autowired
    private YxyTradeJhmpService yxyTradeJhmpService;

    @Autowired
    private AcmTransactionParams acmTransactionParams;

    @Autowired
    private CommonService commonService;

    @Autowired
    private YishengTradeService yishengTradeService;

    @Autowired
    private PayTypeApiService payTypeApiService;

    @Autowired
    private XiaoLuTradeService xiaoLuTradeService;

    /**
     * 拉卡拉商户审核
     *
     * @param reqDto 加密串
     * @return
     */
    @ExcludeInterceptor
    @PostMapping(value = "/lakala/merchant/notice")
    public String lakalaMerchantNotice(@RequestBody LakalaCallBackDTO reqDto, HttpServletRequest httpServletRequest) throws Exception {
        log.info("拉卡拉商户审核");
        try {
            JSONObject jTransaction = parseLakalaParam(reqDto.getData(), httpServletRequest);

            if (commonService.repeatSubmit("lakalaMerchantNotice:" + jTransaction.getString("contractId"))) {
                log.info("重复推送跳过:{}", jTransaction.toJSONString());
            } else {
                // 检查审核状态
                String auditStatus = jTransaction.getString("status");
                if (StringUtils.equals(auditStatus, "SUCCESS")) {
                    // 调用添加商户
                    Result result = yxyTradeService.lakalaMerchantNotice(jTransaction);
                    if (result.isSuccess()) {
                        return "success";
                    }
                } else {
                    log.info("状态非审核通过");
                    return "success";
                }
            }
        } catch (Exception e) {
            log.error("拉卡拉商户审核失败", e);
        }
        throw new RuntimeException("拉卡拉商户审核失败");
    }


    /**
     * 拉卡拉绑机通知
     *
     * @param reqDto 加密串
     * @return
     */
    @ExcludeInterceptor
    @PostMapping(value = "/lakala/merchant/bind")
    public String lakalaMerchantBindNotice(@RequestBody LakalaCallBackDTO reqDto, HttpServletRequest httpServletRequest) {
        log.info("拉卡拉商户绑定");

        try {
            JSONObject jTransaction = parseLakalaParam(reqDto.getData(), httpServletRequest);

            if (commonService.repeatSubmit("lakalaMerchantBind:" + jTransaction.getString("externalCustomerNo"))) {
                log.info("重复推送跳过:{}", jTransaction.toJSONString());
            } else {
                // 检查绑定状态
                String type = jTransaction.getString("type");
                if (StringUtils.equals(type, "BIND")) {
                    // 调用绑定接口
                    Result result = yxyTradeService.lakalaMerchantBind(jTransaction);
                    if (result.isSuccess()) {
                        return "success";
                    }
                } else {
                    log.info("状态非绑定成功， {}", jTransaction);
                    return "success";
                }
            }
        } catch (Exception e) {
            log.error("拉卡拉商户绑定失败", e);
        }
        throw new RuntimeException("拉卡拉商户绑定失败");
    }


    /**
     * 拉卡拉交易推送
     *
     * @param reqDto 加密串
     * @return
     */
    @ExcludeInterceptor
    @PostMapping(value = "/lakala/trade")
    public String lakalaTrade(@RequestBody LakalaCallBackDTO reqDto, HttpServletRequest httpServletRequest) {
        log.info("拉卡拉推送交易流水");

        try {
            JSONObject jTransaction = parseLakalaParam(reqDto.getData(), httpServletRequest);

            if (commonService.repeatSubmit("dealTradeLakala:" + jTransaction.getString("orderNo") + "-" + jTransaction.getString("type"))) {
                log.info("重复推送交易跳过:{}", jTransaction.toJSONString());
            } else {
                Result result = yxyTradeService.lakalaDealTrade(jTransaction);
                if (result.isSuccess()) {
                    return "success";
                }
            }
        } catch (Exception e) {
            log.error("拉卡拉推送交易处理失败", e);
        }
        throw new RuntimeException("拉卡拉推送交易处理失败");
    }

    /**
     * 拉卡拉交易ESIM卡流量费
     *
     * @param reqDto 加密串
     * @return
     */
    @ExcludeInterceptor
    @PostMapping(value = "/lakala/trade/icc")
    public String lakalaTradeIcc(@RequestBody LakalaCallBackDTO reqDto, HttpServletRequest httpServletRequest) {
        log.info("拉卡拉推送流量费流水");

        try {
            JSONObject jTransaction = parseLakalaParam(reqDto.getData(), httpServletRequest);

            if (commonService.repeatSubmit("dealTradeIccLakala:" + jTransaction.getString("logNo"))) {
                log.info("重复推送流量费跳过:{}", jTransaction.toJSONString());
            } else {
                Result result = yxyTradeService.updateTradeIcc(jTransaction);
                if (result.isSuccess()) {
                    return "success";
                }
            }
        } catch (Exception e) {
            log.error("拉卡拉推送流量费处理失败", e);
        }
        throw new RuntimeException("拉卡拉推送流量费处理失败");
    }


    /**
     * 拉卡拉交易手续费
     *
     * @param reqDto 加密串
     * @return
     */
    @ExcludeInterceptor
    @PostMapping(value = "/lakala/trade/fee")
    public String tradeFeeLakala(@RequestBody LakalaCallBackDTO reqDto, HttpServletRequest httpServletRequest) {
        log.info("拉卡拉推送交易手续费流水");

        try {
            JSONObject jTransaction = parseLakalaParam(reqDto.getData(), httpServletRequest);

            if (commonService.repeatSubmit("dealTradeFeeLakala:" + jTransaction.getString("orderNo"))) {
                log.info("重复推送交易手续费跳过:{}", jTransaction.toJSONString());
            } else {
                Result result = yxyTradeService.updateTradeFee(jTransaction);
                if (result.isSuccess()) {
                    return "success";
                }
            }
        } catch (Exception e) {
            log.error("拉卡拉推送交易手续费处理失败", e);
        }
        throw new RuntimeException("拉卡拉交易手续费失败");
    }

    /**
     * 拉卡拉交易D0手续费
     *
     * @param reqDto 加密串
     * @return
     */
    @ExcludeInterceptor
    @PostMapping(value = "/lakala/trade/d0fee")
    public String tradeD0FeeLakala(@RequestBody LakalaCallBackDTO reqDto, HttpServletRequest httpServletRequest) {
        log.info("拉卡拉推送D0手续费");

        try {
            JSONObject jTransaction = parseLakalaParam(reqDto.getData(), httpServletRequest);

            if (commonService.repeatSubmit("dealTradeD0FeeLakala:" + jTransaction.getString("tranJnl"))) {
                log.info("重复推送D0手续费跳过:{}", jTransaction.toJSONString());
            } else {
                Result result = yxyTradeService.updateTradeD0Fee(jTransaction);
                if (result.isSuccess()) {
                    return "success";
                }
            }
        } catch (Exception e) {
            log.error("拉卡拉推送D0手续费处理失败", e);
        }
        throw new RuntimeException("拉卡拉推送D0手续费失败");
    }


    /**
     * 易生回调
     * 交易/商户/费率变更/绑定机具
     *
     * @param httpServletRequest 加密串
     * @return
     */
    @ExcludeInterceptor
    @PostMapping(value = "/yisheng")
    public void yisheng(HttpServletRequest httpServletRequest, HttpServletResponse response) {
        boolean dealResult = true;
        try {
            String decrypt = parseYishengParam(httpServletRequest);
            log.info("易生回调解密后:{}", decrypt);

            JSONObject callBackDataJsonObj = JSONObject.parseObject(decrypt);

            if (Objects.nonNull(callBackDataJsonObj)) {

                Result result;
                String action = callBackDataJsonObj.getString("action");
                if (StringUtils.equals(action, "cus")) {
                    // 商户信息推送
                    result = yishengTradeService.merchantNotify(callBackDataJsonObj);

                } else if (StringUtils.equals(action, "trans")) {
                    // 交易信息推送
                    result = yishengTradeService.transactionNotify(callBackDataJsonObj);

                } else if (StringUtils.equals(action, "modifyBusRate")) {
                    // 商户费率变更通知
                    result = yishengTradeService.merchantRateNotify(callBackDataJsonObj);

                } else if (StringUtils.equals(action, "bindPos")) {
                    // 机具绑定通知
                    result = yishengTradeService.bindPosNotify(callBackDataJsonObj);
                } else {
                    // 其它类型的请求暂不处理
                    result = Result.builder().success();
                }

                if (Objects.isNull(result) || result.isFail()) {
                    dealResult = false;
                }
            }
        } catch (Exception e) {
            log.error("易生回调处理失败", e);
        }

        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
        }
        // 检查PrintWriter对象是否为空
        if (out != null) {
            try {
                // 输出字符串到响应
                out.write(dealResult ? "SUCCESS" : "FAIL");
            } finally {
                // 必须关闭PrintWriter对象
                out.close();
            }
        }
    }

    /**
     * 合利宝交易回调
     */
    @ExcludeInterceptor
    @PostMapping(value = "/hlb/trade/notice")
    public String hlbTradeNotice(@RequestBody JSONObject jRequest, HttpServletRequest httpServletRequest) {
        log.info("合利宝交易回调");
        Map<String, String> payParams = payTypeApiService.getPayParams(PayTypeEnum.HE_LI_BAO, PayFromEnum.merchant);
        try {
            JSONObject jTransaction = HlbSignUtils.decode(payParams, jRequest.toJSONString());
            log.info("合利宝交易回调解密后:{}", jTransaction.toJSONString());
            if (!HlbCommonUtils.ORDER_STATUS_SUCCESS.equals(jTransaction.getString("orderStatus"))) {
                return HlbCommonUtils.RESPONSE_SUCCESS_CODE;
            }

            Result dealResult = yxyTradeService.hlbDealTrade(jTransaction);
            if (dealResult.isSuccess()) {
                return HlbCommonUtils.RESPONSE_SUCCESS_CODE;
            }
        } catch (Exception e) {
            log.error("合利宝交易回调处理失败", e);
        }
        return HlbCommonUtils.RESPONSE_FAIL_CODE;
    }

    /**
     * 中付交易回调
     */
    @ExcludeInterceptor
    @PostMapping(value = "/zfys/trade/notice")
    public String zfTradeNotice(@RequestParam("data") String data) {
        log.info("中付交易回调, data={}", data);
        try {
            JSONObject jTransaction;
            if (StringUtils.startsWith(data, "{") && StringUtils.contains(data, "lakala")) {
                jTransaction = JSONObject.parseObject(data);
            } else {
                Map<String, String> payParams = payTypeApiService.getPayParams(PayTypeEnum.ZHONG_FU, PayFromEnum.merchant);
                String decryptData = YiLianUtil.decryptPushData(data, payParams);
                log.info("中付交易回调解密后:{}", decryptData);
                jTransaction = JSONObject.parseObject(decryptData);
            }

            if (!YiLianUtil.TRADE_STATUS_SUCCESS.equals(jTransaction.getString("trans_status"))) {
                return YiLianUtil.RESPONSE_SUCCESS_CODE;
            }

            Result dealResult = yxyTradeService.zfAndYsDealTrade(jTransaction);
            if (dealResult.isSuccess()) {
                return YiLianUtil.RESPONSE_SUCCESS_CODE;
            }
        } catch (Exception e) {
            log.error("中付交易回调处理失败", e);
        }
        return YiLianUtil.RESPONSE_FAIL_CODE;
    }

    @ExcludeInterceptor
    @PostMapping(value = "/zfys/settle/notice")
    public String zfSettleNotice(@RequestParam("data") String data) {
        log.info("中付结算回调, data={}", data);
        Map<String, String> payParams = payTypeApiService.getPayParams(PayTypeEnum.ZHONG_FU, PayFromEnum.merchant);
        try {
            String decryptData = YiLianUtil.decryptPushData(data, payParams);
            log.info("中付结算回调解密后:{}", decryptData);
            if (StringUtils.startsWith(data, "{") && StringUtils.contains(data, "lakala")) {
                decryptData = data;
            }
            JSONObject jTransaction = JSONObject.parseObject(decryptData);
            if (!StringUtils.equals(jTransaction.getString("status"), "4")) {
                return YiLianUtil.RESPONSE_SUCCESS_CODE;
            }

            Result dealResult = yxyTradeService.zfAndYsUpdateTrade(jTransaction);
            if (dealResult.isSuccess()) {
                return YiLianUtil.RESPONSE_SUCCESS_CODE;
            }
        } catch (Exception e) {
            log.error("中付交易结算回调处理失败", e);
        }
        return YiLianUtil.RESPONSE_FAIL_CODE;
    }


    /**
     * 中付大额码牌交易回调
     */
    @ExcludeInterceptor
    @PostMapping(value = "/zfys/mapai/trade/notice")
    public String zfysMaPaiTradeNotice(@RequestParam("data") String data) {
        log.info("中付大额码牌交易回调, data={}", data);
        try {
            JSONObject jTransaction;
            if (StringUtils.startsWith(data, "{") && StringUtils.contains(data, "lakala")) {
                jTransaction = JSONObject.parseObject(data);
            } else {
                Map<String, String> payParams = payTypeApiService.getPayParams(PayTypeEnum.ZHONG_FU_MAPAI, PayFromEnum.merchant);
                String decryptData = YiLianUtil.decryptPushData(data, payParams);
                log.info("中付大额码牌交易回调解密后:{}", decryptData);
                jTransaction = JSONObject.parseObject(decryptData);
            }

            if (!YiLianUtil.TRADE_STATUS_SUCCESS.equals(jTransaction.getString("trans_status"))) {
                return YiLianUtil.RESPONSE_SUCCESS_CODE;
            }

            Result dealResult = yxyTradeService.zfAndYsDealTrade(jTransaction);
            if (dealResult.isSuccess()) {
                return YiLianUtil.RESPONSE_SUCCESS_CODE;
            }
        } catch (Exception e) {
            log.error("中付大额码牌交易回调处理失败", e);
        }
        return YiLianUtil.RESPONSE_FAIL_CODE;
    }

    /**
     * 聚合码牌交易回调
     */
    @ExcludeInterceptor
    @RequestMapping(value = "/juhe/mapai/trade/notice")
    public String juHeMaPaiTradeNotice(@RequestParam("data") String data) {
        log.info("聚合码牌交易回调, data={}", data);
        try {
            JSONObject jTransaction;
            jTransaction = JSONObject.parseObject(data);
            if (!Objects.equals(jTransaction.getString("State"), "1")) {
                return YiLianUtil.RESPONSE_SUCCESS_CODE;
            }
            Result dealResult = yxyTradeJhmpService.jhmpDealTrade(jTransaction);
            if (dealResult.isSuccess()) {
                return YiLianUtil.RESPONSE_SUCCESS_CODE;
            }
        } catch (Exception e) {
            log.error("聚合码牌交易回调处理失败", e);
        }
        return YiLianUtil.RESPONSE_FAIL_CODE;
    }

    @ExcludeInterceptor
    @PostMapping(value = "/zfys/mapai/settle/notice")
    public String zfysMaPaiSettleNotice(@RequestParam("data") String data) {
        log.info("中付大额码牌结算回调, data={}", data);
        Map<String, String> payParams = payTypeApiService.getPayParams(PayTypeEnum.ZHONG_FU_MAPAI, PayFromEnum.merchant);
        try {
            String decryptData = YiLianUtil.decryptPushData(data, payParams);
            log.info("中付大额码牌结算回调解密后:{}", decryptData);
            if (StringUtils.startsWith(data, "{") && StringUtils.contains(data, "lakala")) {
                decryptData = data;
            }
            JSONObject jTransaction = JSONObject.parseObject(decryptData);
            if (!StringUtils.equals(jTransaction.getString("status"), "4")) {
                return YiLianUtil.RESPONSE_SUCCESS_CODE;
            }

            Result dealResult = yxyTradeService.zfAndYsUpdateTrade(jTransaction);
            if (dealResult.isSuccess()) {
                return YiLianUtil.RESPONSE_SUCCESS_CODE;
            }
        } catch (Exception e) {
            log.error("中付大额码牌交易结算回调处理失败", e);
        }
        return YiLianUtil.RESPONSE_FAIL_CODE;
    }

    /**
     * 银多财交易回调
     */
    @ExcludeInterceptor
    @PostMapping(value = "/ydc/trade/notice")
    public String ydcTradeNotice(@RequestParam("data") String data) {
        log.info("银多财交易回调, data={}", data);
        try {
            JSONObject jTransaction;
            if (StringUtils.startsWith(data, "{") && StringUtils.contains(data, "lakala")) {
                jTransaction = JSONObject.parseObject(data);
            } else {
                Map<String, String> payParams = payTypeApiService.getPayParams(PayTypeEnum.YING_DUO_CAI, PayFromEnum.merchant);
                String decryptData = YdcDecryptUtil.decrypt(data, payParams.get("aesKey"));
                log.info("银多财交易回调解密后:{}", decryptData);
                jTransaction = JSONObject.parseObject(decryptData);
            }
            jTransaction = jTransaction.getJSONObject("jsonData");

            if (!YiLianUtil.TRADE_STATUS_SUCCESS.equals(jTransaction.getString("transStatus"))) {
                return YiLianUtil.RESPONSE_SUCCESS_CODE;
            }

            Result dealResult = yxyTradeService.ydcDealTrade(jTransaction);
            if (dealResult.isSuccess()) {
                return YiLianUtil.RESPONSE_SUCCESS_CODE;
            }
        } catch (Exception e) {
            log.error("银多财交易回调处理失败", e);
        }
        return YiLianUtil.RESPONSE_FAIL_CODE;
    }

    /**
     * 银多财结算通知
     */
    @ExcludeInterceptor
    @PostMapping(value = "/ydc/settle/notice")
    public String ydcSettleNotice(@RequestParam("data") String data) {
        log.info("银多财结算回调, data={}", data);
        JSONObject jSettle;
        if (StringUtils.startsWith(data, "{") && StringUtils.contains(data, "lakala")) {
            jSettle = JSONObject.parseObject(data);
        } else {
            Map<String, String> payParams = payTypeApiService.getPayParams(PayTypeEnum.YING_DUO_CAI, PayFromEnum.merchant);
            String decryptData = YdcDecryptUtil.decrypt(data, payParams.get("aesKey"));
            log.info("银多财结算回调解密后:{}", decryptData);
            jSettle = JSONObject.parseObject(decryptData);
        }
        jSettle = jSettle.getJSONObject("jsonData");

        if (!StringUtils.equals(jSettle.getString("status"), "SETTLE_SUCCESS")) { //结算成功
            return YiLianUtil.RESPONSE_SUCCESS_CODE;
        }

        Result dealResult = yxyTradeService.ydcUpdateTrade(jSettle);
        if (dealResult.isSuccess()) {
            return YiLianUtil.RESPONSE_SUCCESS_CODE;
        }
        return YiLianUtil.RESPONSE_FAIL_CODE;
    }

    /* 小陆 */
    @ExcludeInterceptor
    @PostMapping(value = "/xiaolu/epos/merchant")
    public String xiaoLuEposMerchantInfo(@RequestBody String data) {
        log.info("小陆电签商户回调, data={}", data);
        JSONObject jMerchant = JSONObject.parseObject(data).getJSONObject("reqdatajson");
        if (!StringUtils.equals(jMerchant.getString("status"), "0")) {
            return XiaoLuUtil.getResponseSuccess().toJSONString();
        }

        Result dealResult = xiaoLuTradeService.eposMerchantNotify(jMerchant);
        if (dealResult.isSuccess()) {
            return XiaoLuUtil.getResponseSuccess().toJSONString();
        }
        return XiaoLuUtil.getResponseFail().toJSONString();
    }

    @ExcludeInterceptor
    @PostMapping(value = "/xiaolu/epos/terminal")
    public String xiaoLuEposTerminalBind(@RequestBody String data) {
        log.info("小陆电签商户回调, data={}", data);
        JSONObject jMerchant = JSONObject.parseObject(data).getJSONObject("reqdatajson");
        if (!StringUtils.equals(jMerchant.getString("status"), "0")) {
            return XiaoLuUtil.getResponseSuccess().toJSONString();
        }

        Result dealResult = xiaoLuTradeService.eposTerminalBindNotify(jMerchant);
        if (dealResult.isSuccess()) {
            return XiaoLuUtil.getResponseSuccess().toJSONString();
        }
        return XiaoLuUtil.getResponseFail().toJSONString();
    }

    @ExcludeInterceptor
    @PostMapping(value = "/xiaolu/epos/trade")
    public String xiaoLuEposTrade(@RequestBody String data) {
        log.info("小陆电签交易回调, data={}", data);
        JSONObject jTransaction = JSONObject.parseObject(data).getJSONObject("reqdatajson");
        //交易状态 S:成功,C:冲正
        if (!StringUtils.equals(jTransaction.getString("refund"), "0")) { //结算成功
            return XiaoLuUtil.getResponseSuccess().toJSONString();
        }

        Result dealResult = xiaoLuTradeService.eposTransactionNotify(jTransaction);
        if (dealResult.isSuccess()) {
            return XiaoLuUtil.getResponseSuccess().toJSONString();
        }
        return XiaoLuUtil.getResponseFail().toJSONString();
    }

    @ExcludeInterceptor
    @PostMapping(value = "/xiaolu/epos/icc")
    public String xiaoLuEposIcc(@RequestBody String data) {
        log.info("小陆电签通讯费回调, data={}", data);
        JSONObject jIcc= JSONObject.parseObject(data).getJSONObject("reqdatajson");
        Result dealResult = xiaoLuTradeService.eposIccNotify(jIcc);
        if (dealResult.isSuccess()) {
            return XiaoLuUtil.getResponseSuccess().toJSONString();
        }
        return XiaoLuUtil.getResponseFail().toJSONString();
    }
    //电签end------------------------------------------------------------------------------------------------------------
    @ExcludeInterceptor
    @PostMapping(value = "/xiaolu/spos/merchant")
    public String xiaoLuSposMerchantInfo(@RequestBody String data) {
        log.info("小陆微智能商户回调, data={}", data);
        JSONObject jMerchant = JSONObject.parseObject(data).getJSONObject("reqdatajson");
        if (!StringUtils.equals(jMerchant.getString("status"), "0")) {
            return XiaoLuUtil.getResponseSuccess().toJSONString();
        }
        String sign= JSONObject.parseObject(data).getString("sign");
        String aesKey="";
        Map<String, String> payParams = payTypeApiService.getPayParams(PayTypeEnum.XIAO_LU_SPOS, PayFromEnum.merchant);
        if (StringUtils.isNotEmpty(sign)) {
            aesKey = XiaoLuUtil.sm2Decrypt(sign, payParams.get("yrbPrivateKey"));
        }

        Result dealResult = xiaoLuTradeService.sposMerchantNotify(jMerchant, aesKey);
        if (dealResult.isSuccess()) {
            return XiaoLuUtil.getResponseSuccess().toJSONString();
        }
        return XiaoLuUtil.getResponseFail().toJSONString();
    }
    @ExcludeInterceptor
    @PostMapping(value = "/xiaolu/spos/terminal")
    public String xiaoLuSposTerminalBind(@RequestBody String data) {
        log.info("小陆微智能机具绑定回调, data={}", data);
        JSONObject jTerminal = JSONObject.parseObject(data).getJSONObject("reqdatajson");
        //只处理2POS
        if (!StringUtils.equals(jTerminal.getString("equiptype"), "2")) {
            return XiaoLuUtil.getResponseSuccess().toJSONString();
        }

        Result dealResult = xiaoLuTradeService.sposTerminalBindNotify(jTerminal);
        if (dealResult.isSuccess()) {
            return XiaoLuUtil.getResponseSuccess().toJSONString();
        }
        return XiaoLuUtil.getResponseFail().toJSONString();
    }

    @ExcludeInterceptor
    @PostMapping(value = "/xiaolu/spos/trade")
    public String xiaoLuSposTrade(@RequestBody String data) {
        log.info("小陆微智能交易回调, data={}", data);
        JSONObject jTransaction = JSONObject.parseObject(data).getJSONObject("reqdatajson");
        //交易状态 S:成功,C:冲正
        if (!StringUtils.equals(jTransaction.getString("refund"), "0")) { //结算成功
            return XiaoLuUtil.getResponseSuccess().toJSONString();
        }

        Result dealResult = xiaoLuTradeService.sposTransactionNotify(jTransaction);
        if (dealResult.isSuccess()) {
            return XiaoLuUtil.getResponseSuccess().toJSONString();
        }
        return XiaoLuUtil.getResponseFail().toJSONString();
    }

    @ExcludeInterceptor
    @PostMapping(value = "/xiaolu/spos/icc")
    public String xiaoLuSposIcc(@RequestBody String data) {
        log.info("小陆微智能通讯费回调, data={}", data);
        JSONObject jIcc= JSONObject.parseObject(data).getJSONObject("reqdatajson");
        Result dealResult = xiaoLuTradeService.sposIccNotify(jIcc);
        if (dealResult.isSuccess()) {
            return XiaoLuUtil.getResponseSuccess().toJSONString();
        }
        return XiaoLuUtil.getResponseFail().toJSONString();
    }
    /* 小陆 -end */

    /**
     * 解析请求参数
     *
     * @param httpServletRequest
     * @return
     */
    private String parseYishengParam(HttpServletRequest httpServletRequest) {

        String body = "";
        try {

            StringBuilder sb = new StringBuilder();
            BufferedReader reader = null;
            InputStream inputStream = httpServletRequest.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            body = sb.toString();
            log.info("易生推送原数据：{}", body);
            // 方便测试免签
            String mockDecrypt = httpServletRequest.getHeader("mockDecrypt");
            if (StringUtils.equals(mockDecrypt, acmTransactionParams.getYishengCallBackPriKey())) {
                return body;
            }
            Map<String, String> payParams = payTypeApiService.getPayParams(PayTypeEnum.YI_SHENG, PayFromEnum.merchant);
            String decodeContext = DecryptUtil.decrypt(payParams.get("privateKey"), body);
            return decodeContext;
        } catch (Exception e) {
            log.error("parseYishengParam error. body=" + body, e);
        }
        return null;
    }


    /**
     * 解析拉卡拉请求参数
     *
     * @param httpServletRequest
     * @return
     */
    private JSONObject parseLakalaParam(String body, HttpServletRequest httpServletRequest) {

        try {
            String ip = RequestUtil.ipAddress(httpServletRequest);
            log.info("拉卡拉回调请求ip:{}", ip);

            Map<String, String> payParams = payTypeApiService.getPayParams(PayTypeEnum.LAKALA_EPOS, PayFromEnum.merchant);
            // 方便测试免签
            String decrypt;
            String mockDecrypt = httpServletRequest.getHeader("mockDecrypt");
            if (StringUtils.equals(mockDecrypt, "1")) {
                decrypt = body;
            } else {
                decrypt = RSAUtil.decrypt(payParams.get("publicKey"), body);
            }
            log.info("拉卡拉参数解密后:{}", decrypt);

            return JSONObject.parseObject(decrypt);
        } catch (Exception e) {
            log.error("parseLakalaParam error. body=" + body, e);
        }

        return null;
    }


}
